package com.pingan.mybatis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * @AUTHOR:LIUCHAO;
 * @DATE: 2020/11/27 9:32
 */
public class PropUtil {
    private static Logger logger = LoggerFactory.getLogger(PropUtil.class);

    private static Properties properties = new Properties();
    private static String filename;

    public static String getProperty(String key) {
        return properties.getProperty(key);
    }

    /**
     * 配置文件参数重写
     *
     * @param key
     * @param value
     */
    public static void setProperty(String key, String value) {
        try {
            FileInputStream inputStream = new FileInputStream(
                    new File(Thread.currentThread().getContextClassLoader().getResource(filename).getPath()));
            Properties prop = new Properties();
            prop.load(inputStream);

            prop.setProperty(key, value);

            FileOutputStream outputStream = new FileOutputStream(
                    new File(Thread.currentThread().getContextClassLoader().getResource(filename).getPath()));
            prop.store(outputStream, "Update '" + key + "' value");
            outputStream.flush();
            outputStream.close();
            properties.setProperty(key, value);
        } catch (FileNotFoundException e) {
            logger.error("load properties file error:" + e);
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("load properties file error:" + e);
            e.printStackTrace();
        }
    }

    /**
     * 启动时加载properties配置文件
     *
     * @param filePath
     */
    public static void loadFile(String filePath) {
        try {
            properties.clear();
            filename = filePath;
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath));
        } catch (IOException e) {
            logger.error("加载配置文件错误:" + e);
            e.printStackTrace();
        }
    }
}